<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>题库管理</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <link rel="stylesheet" type="text/css" href="/mp/css/base.css" media="all">
  <link rel="stylesheet" type="text/css" href="/mp/css/mm_style.css" media="all">
  <link rel="stylesheet" href="../../../layuiadmin/layui/css/layui.css" media="all">
  <link rel="stylesheet" type="text/css" href="/mp/swiper4/css/swiper.min.css" media="all">
  <script>
      //获取浏览器页面可见高度和宽度
      var _PageHeight = document.documentElement.clientHeight,
          _PageWidth = document.documentElement.clientWidth;
      //计算loading框距离顶部和左部的距离（loading框的宽度为215px，高度为61px）
      var _LoadingTop = _PageHeight > 61 ? (_PageHeight - 61) / 2 : 0,
          _LoadingLeft = _PageWidth > 215 ? (_PageWidth - 215) / 2 : 0;
      //在页面未加载完毕之前显示的loading Html自定义内容
      var _LoadingHtml = '<div id="loadingDiv" style="position:absolute;left:0;width:100%;height:' + _PageHeight + 'px;top:0;background:#f3f8ff;opacity:1;filter:alpha(opacity=80);z-index:10000;"><div style="position: absolute; cursor1: wait; left: ' + _LoadingLeft + 'px; top:' + _LoadingTop + 'px; width: auto; height: 57px; line-height: 57px; padding-left: 50px; padding-right: 5px; background: #fff no-repeat scroll 5px 10px; border: 2px solid #95B8E7; color: #696969; font-family:\'Microsoft YaHei\';">页面加载中，请等待...</div></div>';
      //呈现loading效果
      document.write(_LoadingHtml);
      //监听加载状态改变
      document.onreadystatechange = completeLoading;

      //加载状态为complete时移除loading效果
      function completeLoading() {
          if (document.readyState == "complete") {
              var loadingMask = document.getElementById('loadingDiv');
              loadingMask.parentNode.removeChild(loadingMask);
          }
      }

  </script>
</head>
<body>
<div class="mHeader">
  <span hidden id="pageSize"></span>
  <h4 class="" id="examTitle">培训名称</h4>
  <span class="countDownTime"><img src="/mp/images/time.png" class="timeIcon"/><span id="downTime">00:00</span></span>
</div>
<script id="demo" type="text/html">
  <div class="swiper-container">
    <div class="swiper-wrapper">
    {{#  layui.each(d, function(index, item){ }}
      <div class="swiper-slide" style="height:1000px">
        <div class="content pab160 pat140">
          {{#  if(item.questionType === 2){ }}
          <p class="fsSmall30 col3 topicItem"><img src="/mp/images/duoxuan.png" alt="" class="dxIcon">{{ item.questionContent }}</p>
          <div class="popCheckOne">
            <input type="checkbox" value="A" name="dx" id="A{{index}}" chacked="true">
            <label for="A{{index}}" class="col3">A.{{ item.optionA }}</label>
          </div>
          <div class="popCheckOne">
            <input type="checkbox" value="B" name="dx"  id="B{{index}}" chacked="true">
            <label for="B{{index}}" class="col3">B.{{ item.optionB }}</label>
          </div>
          {{#  if(item.optionC!=null && item.optionC.length>0){ }}
            <div class="popCheckOne">
              <input type="checkbox" value="C" name="dx" id="C{{index}}" chacked="true">
              <label for="C{{index}}" class="col3">C.{{ item.optionC }}</label>
            </div>
          {{#  } }}
          {{#  if(item.optionD!=null && item.optionD.length>0){ }}
            <div class="popCheckOne">
              <input type="checkbox" value="D" name="dx" id="D{{index}}" chacked="true">
              <label for="D{{index}}" class="col3">D.{{ item.optionD }}</label>
            </div>
          {{#  } }}
          {{#  if(item.optionE!=null && item.optionE.length>0){ }}
            <div class="popCheckOne">
              <input type="checkbox" value="E" name="dx" id="E{{index}}" chacked="true">
              <label for="E{{index}}" class="col3">E.{{ item.optionE }}</label>
            </div>
          {{#  } }}
          {{#  if(item.optionF!=null && item.optionF.length>0){ }}
            <div class="popCheckOne">
              <input type="checkbox" value="F" name="dx" id="F{{index}}" chacked="true">
              <label for="F{{index}}" class="col3">F.{{ item.optionF }}</label>
            </div>
          {{#  } }}
          {{# } else  { }}
          <p class="fsSmall30 col3 topicItem padd20">
              {{#  if(item.questionType === 1){ }}
                  <img src="/mp/images/dx.png" alt="" class="dxIcon">
              {{# } else  { }}
                  <img src="/mp/images/pd.png" alt="" class="dxIcon">
              {{#  } }}
              {{ item.questionContent }}
          </p>
          <div class="singleRadio padd20">
            <div class="radios">
              <input type="radio" value="A" name="dx{{index}}" id="SA{{index}}" >
              <label for="SA{{index}}" class="radioStyle radioStyleOther">A.{{ item.optionA }}</label>
            </div>
            <div class="radios">
              <input type="radio" value="B" name="dx{{index}}" id="SB{{index}}" >
              <label for="SB{{index}}" class="radioStyle radioStyleOther">B.{{ item.optionB }}</label>
            </div>
            {{#  if(item.optionC!=null && item.optionC.length>0){ }}
            <div class="radios">
              <input type="radio" value="C" name="dx{{index}}" id="SC{{index}}" >
              <label for="SC{{index}}" class="radioStyle radioStyleOther">C.{{ item.optionC }}</label>
            </div>
            {{#  } }}
            {{#  if(item.optionD!=null && item.optionD.length>0){ }}
            <div class="radios">
              <input type="radio" value="D" name="dx{{index}}" id="SD{{index}}" >
              <label for="SD{{index}}" class="radioStyle radioStyleOther">D.{{ item.optionD }}</label>
            </div>
            {{#  } }}
            {{#  if(item.optionE!=null && item.optionE.length>0){ }}
            <div class="radios">
              <input type="radio" value="E" name="dx{{index}}" id="SE{{index}}" >
              <label for="SE{{index}}" class="radioStyle radioStyleOther">E.{{ item.optionE }}</label>
            </div>
            {{#  } }}
            {{#  if(item.optionF!=null && item.optionF.length>0){ }}
            <div class="radios">
              <input type="radio" value="F" name="dx{{index}}" id="SF{{index}}" >
              <label for="SF{{index}}" class="radioStyle radioStyleOther">F.{{ item.optionF }}</label>
            </div>
            {{#  } }}
          </div>
          {{#  } }}
        </div>
      </div>
    {{#  }); }}
    </div>
  </div>
    {{#  if(d.length === 0){ }}
    无数据
    {{#  } }}
</script>
<div id="view"></div>
<!-- start：题目列表 -->
<input class="confirm-btn" type="button" value="确认答案">
<div class="Mbottom tac">
  <a class="jiaojuanBtn fl"><img src="/mp/images/jiaojuan.png">交卷</a>
  <span class="page" id="page" style="margin-left: -32px;">1/5</span>
</div>

</body>
<script src="../../../layuiadmin/layui/layui.js"></script>
<script type="text/javascript" src="/mp/js/mobile.js"></script>
<script type="text/javascript" src="/mp/js/common/common.js"></script>
<script type="text/javascript" src="/mp/swiper4/js/swiper.min.js"></script>
<script type="text/javascript" src="/mp/layer_mobile/layer.js"></script>
<script>
    layui.config({
        base: '../../../layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'laytpl','layer'], function(){
        var laytpl = layui.laytpl
            ,$ = layui.$;

        //渲染页面
        $(".confirm-btn").hide();
        var trainId = getQueryString("trainId");
        var identifier = getQueryString("identifier");
        console.log(identifier);
        var examSet =[];
        //获取培训设置方法
        $.ajax({
                url:"/mp/train/getTrainSet",
                async:false,
                type:"get",
                data:{
                    trainId :trainId
                },
                dataType:"json",
                success:function (result) {
                    examSet = result.data;
                }
        });
        $("#examTitle").text(examSet.trainContent);
        var data =[];
        //获取考题方法
        $.ajax({
                url:"/mp/train/getQuestions",
                async:false,
                type:"get",
                data:{
                    trainId :trainId
                },
                dataType:"json",
                success:function (result) {
                    data = result;
                }
        });
        var getTpl = demo.innerHTML
            ,view = document.getElementById('view');
        laytpl(getTpl).render(data, function(html){
            view.innerHTML = html;
        });
        //页面滑动
        var mySwiper = new Swiper('.swiper-container',{
            on: {
                init: function(){
                    $("#page").html("1/"+data.length);
                    var index = parseInt(this.activeIndex);
                    if($(".swiper-slide").eq(index).find('img').attr('src') == "/mp/images/duoxuan.png") {//如果是多选
                        $(".confirm-btn").show();
                    }else{
                        $(".confirm-btn").hide();
                    }
                    $("#pageSize").val(0);
                },
                slideChangeTransitionStart: function(){
                    window.scrollTo(0,0);
                    var index = parseInt(this.activeIndex);
                    if($(".swiper-slide").eq(index).find('img').attr('src') == "/mp/images/duoxuan.png") {//如果是多选
                        $(".confirm-btn").show();
                    }else{
                        $(".confirm-btn").hide();
                    }
                    $("#pageSize").val(index);
                    $("#page").html((index+1)+"/"+data.length);

                }
            }
        });
        var answer = data;
        for(var i = 0;i<answer.length;i++){
            answer[i].isPass = 0;
        }
        localStorage.setItem("answerItem",JSON.stringify(answer));
        //记录选项
        $(".swiper-slide").on("click","input",function () {
            var index = parseInt($("#pageSize").val());
            var hisOption = "";
            //存储答案
            if($(".swiper-slide").eq(index).find('img').attr('src') == "/mp/images/duoxuan.png"){//如果是多选
                $(".swiper-slide").eq(index).find("input[name='dx']:checked").each(function(i){
                    hisOption += ","+$(this).val();
                });
                hisOption = hisOption.substr(1);
            }else{//否则为单选和判断时
                hisOption = $(this).val();
            }
            answer[index].hisOption = hisOption;
            //判断是否答对
            if(hisOption == answer[index].questionAnswer){
                answer[index].isPass = 1;
            }else{
                answer[index].isPass = 0;
            }
            if(answer[index].questionType != 2){
                setTimeout(function () {
                    mySwiper.slideNext();
                },500);
            }
            localStorage.setItem("answerItem",JSON.stringify(answer));
        });
        //复选框 确认按钮事件
        $(".confirm-btn").click(function(){
            var index = parseInt($("#pageSize").val());
            if($(".swiper-slide").length-1 == index){
                //提交
                $(".jiaojuanBtn").click();
            }else{
                setTimeout(function () {
                    mySwiper.slideNext();
                },500);
            }
        });
        //开启倒计时
        var timer = resetTime(examSet.trainTime-1,answer,examSet);
        //倒计时方法
        function resetTime(time,answer,examSet){
            var timer=null;
            var m=time;
            var s=60;
            var min = m>9?m:"0"+m;
            var second = s>9?s:"0"+s;
            $("#downTime").html(min+':'+second);
            function countDown(){
                s--;
                if(s==0 && m>0){
                    m--;
                    s=60;
                }
                if(m==0 && s==0){
                    m='00';
                    s='00';
                    clearInterval(timer);
                    countDownSubmit(answer,examSet);
                }
                var min = m>9?m:"0"+m;
                var second = s>9?s:"0"+s;
                $("#downTime").html(min+':'+second);
                //$(".countDownTime").html('<img src="/mp/images/time.png" class="timeIcon"/>'+min+':'+second);
            }
            timer=setInterval(countDown,1000);
        }
        //按钮倒计时
        function submitDisabledTime(time){
            var timer=null;
            var m=time;
            $(".jiaojuanBtn").css("pointer-events","none");
            $(".jiaojuanBtn").html('<img src="/mp/images/jiaojuan.png">请等待'+m+'秒');
            function countDown(){
                m--;
                $(".jiaojuanBtn").html('<img src="/mp/images/jiaojuan.png">请等待'+m+'秒');
                if(m==0){
                    $(".jiaojuanBtn").html('<img src="/mp/images/jiaojuan.png">交卷');
                    $(".jiaojuanBtn").css("pointer-events","");
                    clearInterval(timer);
                }
            }
            timer=setInterval(countDown,1000);
        }
        //正常提交：计算分数，耗时，停止计时器，题目数量，是否通过
        function result(answer,examSet,timer) {
            submitDisabledTime(60);
            var result = [];
            var score = 0;
            for(var i in answer){
                if(answer[i].isPass == 1){
                    score++;
                }
            }
            result.score = score;
            result.resultCount = answer.length;
            result.useTime = getUseTime(examSet.trainTime,$("#downTime").html());
            result.isPass = score >= examSet.passNum ? 1 : 0;
            localStorage.setItem("Other",result.score+","+result.useTime+","+result.isPass);
            if(timer != null){
                clearTimeout(timer);
            }
            return result;
        }
        //正常提交
        $(".jiaojuanBtn").click(function(){
            //已答题数
            var answer = JSON.parse(window.localStorage.getItem("answerItem"));
            var length = 0;
            for(var a= 0;a<answer.length;a++){
                if(answer[a].isPass!=null){
                    length++;
                }
            }
            var count = $(".swiper-slide").length;
            //全部答完
                if(length == count){
                    var confirm = layer.open({
                        content: '您确定要提交么？'
                        ,btn: ['确认提交', '继续答题']
                        ,yes: function(index){
                            //确认提交
                            var loadingLayer = layer.open({type: 2});
                            layer.close(confirm);
                            var resultParameter = result(answer,examSet,timer);
                            var ajaxTimeOut = $.ajax({    //将网络请求事件赋值给变量ajaxTimeOut
                                url: "/mp/train/submitAnswer",
                                type: "POST",
                                dataType: "json",
                                data: {
                                    identifier:identifier,
                                    trainId:trainId,
                                    useTime:resultParameter.useTime,
                                    isPass:resultParameter.isPass,
                                    score:resultParameter.score,
                                    answer:localStorage.getItem("answerItem")
                                },
                                timeout: 20000, //通过timeout属性，设置超时时间
                                success: function (result) {
                                    if(result.code==0){
                                        var data = result.data;
                                        location.href = "/view/mp/mp-answer";
                                    }else{
                                        layer.close(loadingLayer);
                                        layer.open({
                                            content: result.msg
                                            ,btn: '我知道了'
                                        });
                                    }
                                },
                                error: function (xhr, status, err) {
                                    layer.close(loadingLayer);
                                },
                                complete: function (XMLHttpRequest, status) { //当请求完成时调用函数
                                    if (status == 'timeout') {//status == 'timeout'意为超时,status的可能取值：success,notmodified,nocontent,error,timeout,abort,parsererror
                                        ajaxTimeOut.abort(); //取消请求
                                        $("#loading").hide();
                                        //提示 请求超时
                                        layer.close(loadingLayer);
                                        layer.open({
                                            content: '请求超时，请检查网络！'
                                            ,btn: '我知道了'
                                        });
                                    }
                                }
                            });
                        }
                    });
                }else{
                    layer.open({
                        content: '您还有'+(count-length)+'道题目未答'
                        ,btn: '我知道了'
                    });
                }
        });
        //自动提交：计算分数，耗时，停止计时器，题目数量，是否通过
        function resultAuto(answer,examSet) {
            var result = [];
            var score = 0;
            for(var i in answer){
                if(answer[i].isPass == 1){
                    score++;
                }
            }
            result.score = score;
            result.resultCount = answer.length;
            result.useTime = getUseTime(examSet.trainTime,$("#downTime").html());
            result.isPass = score >= examSet.passNum ? 1:0;
            localStorage.setItem("Other",result.score+","+result.useTime+","+result.isPass);
            return result;
        }
        //自动提交
        function countDownSubmit(answer,examSet) {
            var resultParameter = resultAuto(answer,examSet);
            $.post("/mp/train/submitAnswer",{
                identifier:identifier,
                trainId:trainId,
                useTime:resultParameter.useTime,
                isPass:resultParameter.isPass,                score:resultParameter.score,
                answer:localStorage.getItem("answerItem")
            },function(result){
                if(result.code==0){
                    var data = result.data;
                    location.href = "/view/mp/mp-answer";
                }else{
                    layer.open({
                        content: result.msg
                        ,btn: '我知道了'
                    });
                }
            });
        }
    });

</script>
</html>